﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Localization;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Validation;

namespace ERP.MaterialTypes;

public class MaterialTypeService : ERPAppService
{
#pragma warning disable CS8618
    public IRepository<MaterialType> MaterialTypeRepository { get; set; }
#pragma warning restore CS8618

    public async Task CreateAsync(MaterialTypeCreateInput input)
    {
        await MaterialTypeRepository.InsertAsync(new MaterialType(input.Name, input.Description));
    }

    public async Task UpdateAsync(Guid id, MaterialTypeUpdateInput input)
    {
        var materialType = await MaterialTypeRepository.GetAsync(t => t.Id == id);
        materialType.Update(input.Name, input.Description);
        await MaterialTypeRepository.UpdateAsync(materialType);
    }

    public async Task DeleteAsync(Guid id)
    {
        await MaterialTypeRepository.DeleteAsync(t => t.Id == id);
    }

    public async Task<MaterialTypeDto> GetAsync(Guid id)
    {
        var materialType = await MaterialTypeRepository.GetAsync(t => t.Id == id);
        return ObjectMapper.Map<MaterialType, MaterialTypeDto>(materialType);
    }

    public async Task<PagedResultDto<MaterialTypeDto>> GetListAsync(GetMaterialTypeListInput input)
    {
        var queryable = (await MaterialTypeRepository.GetQueryableAsync())
            .WhereIf(!string.IsNullOrWhiteSpace(input.Name), t => t.Name == input.Name);

        var totalCount = await AsyncExecuter.CountAsync(queryable);

        var materialTypes = await AsyncExecuter.ToListAsync(queryable.Skip(input.SkipCount).Take(input.MaxResultCount));

        return new PagedResultDto<MaterialTypeDto>(totalCount, ObjectMapper.Map<List<MaterialType>, List<MaterialTypeDto>>(materialTypes));
    }

    public async Task<string> GreetingAsync(int input)
    {
        await Task.CompletedTask;

        if ( input > 10 && input < 20 )
        {
            throw new UserFriendlyException(L["hello", "Perry"]);
        }
        if ( input > 20 )
        {
            throw new BusinessException("Abcd:aaa")
                .WithData("name", "孙悟空");
        }

        return L.GetString("hello", "张三");
    }
}